package info.empathymobile.forecast.testenv.business;

import info.empathymobile.forecast.testenv.beans.TestBaseData;
import info.empathymobile.forecast.testenv.beans.TestLog;
import info.empathymobile.forecast.testenv.database.DatabaseHelper;
import info.empathymobile.forecast.testenv.database.OrmLiteBase;

import java.sql.SQLException;
import java.util.List;

import android.content.Context;

import com.j256.ormlite.dao.RuntimeExceptionDao;

public class LocalDBConnection {

	private RuntimeExceptionDao<TestBaseData, Integer> testBaseDataDao = null;
	private RuntimeExceptionDao<TestLog, Integer> testLogDao = null;

	public LocalDBConnection(Context context){
		this.testBaseDataDao = ((OrmLiteBase<DatabaseHelper>)context).getHelper().getTestBaseDataRuntimeDao();
		this.testLogDao = ((OrmLiteBase<DatabaseHelper>)context).getHelper().getTestLogRuntimeDao();
	}
	
	public int saveTestBaseDataCollection(List<TestBaseData> testBaseDataCollection){
		int createdCount = 0;
		for (TestBaseData testBaseData : testBaseDataCollection) {
			if(getTestBaseDataByParams(testBaseData)==null){
				createdCount += testBaseDataDao.create(testBaseData);
			}
		}
		return createdCount;
	}

	public int saveTestLogCollection(List<TestLog> results) {
		int createdCount = 0;
		for (TestLog testLog : results) {
			createdCount += testLogDao.create(testLog);
		}
		return createdCount;
	}
	
	public TestBaseData getTestBaseDataByParams(TestBaseData params) {
		try {
			List<TestBaseData> queried = testBaseDataDao.queryBuilder()
					.where()
						.eq("userUUID", params.getUserUUID())
							.and()
						.eq("usedThreshold", params.getUsedThreshold())
							.and()
						.eq("usedDaysAgo", params.getUsedDaysAgo())
							.and()
						.eq("baseDataType", params.getBaseDataType())
				.query();
			
			if(!queried.isEmpty()){
				return queried.get(0);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	public int deleteTestLogById(List<Integer> notSyncronizedIds) {
		return testLogDao.deleteIds(notSyncronizedIds);
	}

	public List<TestLog> getAllTestLogs() {
		return testLogDao.queryForAll();
	}
}
